/*
 * MainForm.java
 *
 * Created on March 20, 2006, 9:23 AM
 */

/**
 *
 * @author  Sujal Bista
 */

import java.awt.BorderLayout;
import javax.swing.*;
import java.lang.Thread;
import java.lang.Runnable;
import java.util.Vector;
import java.lang.reflect.Array;
import java.util.HashSet;
import java.sql.SQLException;
import java.lang.Integer;
import java.lang.Math;


public class MainForm extends javax.swing.JFrame {
    
    showOutput output;
    Database database;
    Summary finalSummary;
    
    /** Creates new form MainForm */
    public MainForm(){

        //set popup to false
        globalData.initGlobalData();
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
        initDatabase();
        initComponents();
        initSoftware();
        
        
        output=new showOutput(null);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel3 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        GroupGenderC = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        EventC = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        AthleteC = new javax.swing.JComboBox();
        MainP = new javax.swing.JPanel();
        StartB = new javax.swing.JButton();
        ShowB = new javax.swing.JButton();
        ResetB = new javax.swing.JButton();
        PublishB = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        scoreAL = new javax.swing.JLabel();
        scoreAF = new javax.swing.JTextField();
        scoreBF = new javax.swing.JTextField();
        scoreBL = new javax.swing.JLabel();
        scoreCL = new javax.swing.JLabel();
        scoreCF = new javax.swing.JTextField();
        finalScoreL = new javax.swing.JLabel();
        finalF = new javax.swing.JTextField();
        ReasonCL = new javax.swing.JTextArea();
        Reason = new javax.swing.JTextField();
        HeadDeduction = new javax.swing.JTextField();
        Head2 = new javax.swing.JTextArea();
        EvaluateB = new javax.swing.JButton();
        SummaryAF = new javax.swing.JTextField();
        SummaryCL = new javax.swing.JTextArea();
        SummaryAL = new javax.swing.JTextArea();
        SummaryBL = new javax.swing.JTextArea();
        SummaryBF = new javax.swing.JTextField();
        SummaryCF = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        ExitM = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Wushu Judging");
        setMinimumSize(new java.awt.Dimension(1024, 104));
        setName("MainFrame"); // NOI18N
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel3.setMinimumSize(new java.awt.Dimension(1324, 33));
        jPanel3.setPreferredSize(new java.awt.Dimension(1024, 32));
        jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Age/Experience/Gender");
        jPanel3.add(jLabel3);

        GroupGenderC.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        GroupGenderC.setPreferredSize(new java.awt.Dimension(250, 22));
        GroupGenderC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                GroupGenderCActionPerformed(evt);
            }
        });
        jPanel3.add(GroupGenderC);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Event");
        jPanel3.add(jLabel1);

        EventC.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        EventC.setEnabled(false);
        EventC.setPreferredSize(new java.awt.Dimension(250, 22));
        EventC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EventCActionPerformed(evt);
            }
        });
        jPanel3.add(EventC);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Athlete");
        jPanel3.add(jLabel2);

        AthleteC.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        AthleteC.setEnabled(false);
        AthleteC.setPreferredSize(new java.awt.Dimension(250, 22));
        AthleteC.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AthleteCActionPerformed(evt);
            }
        });
        jPanel3.add(AthleteC);

        getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1130, 40));

        MainP.setMaximumSize(new java.awt.Dimension(32767, 34));
        MainP.setPreferredSize(new java.awt.Dimension(407, 33));
        MainP.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        StartB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        StartB.setText("Start (1)");
        StartB.setEnabled(false);
        StartB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StartBActionPerformed(evt);
            }
        });
        MainP.add(StartB, new org.netbeans.lib.awtextra.AbsoluteConstraints(5, 5, -1, 30));

        ShowB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        ShowB.setEnabled(false);
        ShowB.setLabel("Stop, Show, & Save (2)");
        ShowB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ShowBActionPerformed(evt);
            }
        });
        MainP.add(ShowB, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 5, -1, 30));
        ShowB.getAccessibleContext().setAccessibleName("Stop, Show, & Save (4)");

        ResetB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        ResetB.setText("Reset");
        ResetB.setEnabled(false);
        ResetB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ResetBActionPerformed(evt);
            }
        });
        MainP.add(ResetB, new org.netbeans.lib.awtextra.AbsoluteConstraints(940, 5, -1, 30));

        PublishB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        PublishB.setText("Publish");
        PublishB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PublishBActionPerformed(evt);
            }
        });
        MainP.add(PublishB, new org.netbeans.lib.awtextra.AbsoluteConstraints(1040, 5, -1, 30));

        getContentPane().add(MainP, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 1136, 40));

        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
        getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 630, 1130, 30));

        scoreAL.setFont(new java.awt.Font("Bitstream Vera Serif", 0, 36)); // NOI18N
        scoreAL.setText("Score A");
        scoreAL.setToolTipText("");
        scoreAL.setEnabled(false);
        getContentPane().add(scoreAL, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 150, -1, -1));

        scoreAF.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        scoreAF.setEnabled(false);
        getContentPane().add(scoreAF, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 160, 140, 30));

        scoreBF.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        scoreBF.setEnabled(false);
        scoreBF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                scoreBFActionPerformed(evt);
            }
        });
        getContentPane().add(scoreBF, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 210, 140, -1));

        scoreBL.setFont(new java.awt.Font("Bitstream Vera Serif", 0, 36)); // NOI18N
        scoreBL.setText("Score B");
        scoreBL.setEnabled(false);
        getContentPane().add(scoreBL, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 200, -1, -1));

        scoreCL.setFont(new java.awt.Font("Bitstream Vera Serif", 0, 36)); // NOI18N
        scoreCL.setText("Score C");
        scoreCL.setEnabled(false);
        getContentPane().add(scoreCL, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 250, -1, -1));

        scoreCF.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        scoreCF.setEnabled(false);
        getContentPane().add(scoreCF, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 260, 140, -1));

        finalScoreL.setFont(new java.awt.Font("Verdana", 0, 64)); // NOI18N
        finalScoreL.setForeground(new java.awt.Color(0, 0, 204));
        finalScoreL.setText("Final");
        finalScoreL.setEnabled(false);
        getContentPane().add(finalScoreL, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 410, -1, -1));

        finalF.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        finalF.setEnabled(false);
        getContentPane().add(finalF, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 450, 520, -1));

        ReasonCL.setEditable(false);
        ReasonCL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        ReasonCL.setText("Reason");
        ReasonCL.setEnabled(false);
        ReasonCL.setFocusable(false);
        getContentPane().add(ReasonCL, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 310, 90, 30));

        Reason.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        Reason.setForeground(new java.awt.Color(255, 0, 0));
        Reason.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        Reason.setEnabled(false);
        Reason.setPreferredSize(new java.awt.Dimension(150, 20));
        getContentPane().add(Reason, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 310, 180, 30));

        HeadDeduction.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        HeadDeduction.setForeground(new java.awt.Color(255, 0, 0));
        HeadDeduction.setText("0.0");
        HeadDeduction.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        HeadDeduction.setEnabled(false);
        HeadDeduction.setPreferredSize(new java.awt.Dimension(60, 20));
        getContentPane().add(HeadDeduction, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 310, 140, 30));

        Head2.setEditable(false);
        Head2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        Head2.setText("Deductions");
        Head2.setEnabled(false);
        Head2.setFocusable(false);
        getContentPane().add(Head2, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 310, -1, 30));

        EvaluateB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        EvaluateB.setText("Evaluate");
        EvaluateB.setEnabled(false);
        EvaluateB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EvaluateBActionPerformed(evt);
            }
        });
        getContentPane().add(EvaluateB, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 370, -1, 30));

        SummaryAF.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        SummaryAF.setEnabled(false);
        getContentPane().add(SummaryAF, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 160, 530, 30));

        SummaryCL.setEditable(false);
        SummaryCL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        SummaryCL.setText("Summary C");
        SummaryCL.setEnabled(false);
        SummaryCL.setFocusable(false);
        getContentPane().add(SummaryCL, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 260, -1, 30));

        SummaryAL.setEditable(false);
        SummaryAL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        SummaryAL.setText("Summary A");
        SummaryAL.setEnabled(false);
        SummaryAL.setFocusable(false);
        getContentPane().add(SummaryAL, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 160, -1, 30));

        SummaryBL.setEditable(false);
        SummaryBL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        SummaryBL.setText("Summary B");
        SummaryBL.setEnabled(false);
        SummaryBL.setFocusable(false);
        getContentPane().add(SummaryBL, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 210, -1, 30));

        SummaryBF.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        SummaryBF.setEnabled(false);
        getContentPane().add(SummaryBF, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 210, 530, 30));

        SummaryCF.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        SummaryCF.setEnabled(false);
        getContentPane().add(SummaryCF, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 260, 530, 30));

        jMenu1.setText("File");

        ExitM.setText("Exit");
        ExitM.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ExitMActionPerformed(evt);
            }
        });
        jMenu1.add(ExitM);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void PublishBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PublishBActionPerformed
        Publisher pub3 = new Publisher("..\\Data\\ScoresSimple.html");
        pub3.publishScoresSimple(database);
    }//GEN-LAST:event_PublishBActionPerformed

    private void GroupGenderCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_GroupGenderCActionPerformed

        //set current gender and group
        closeAthlete();
        String groupGender = (String) GroupGenderC.getSelectedItem();
        
        //code changed it handles all cases
        if(groupGender.length()!=0)
        {
            globalData.currentAge=groupGender.substring(0, groupGender.indexOf('/'));//.toLowerCase();
            groupGender=groupGender.substring(groupGender.indexOf('/')+1, groupGender.length());
            globalData.currentGroup=groupGender.substring(0, groupGender.indexOf('/'));//.toLowerCase();
            globalData.currentGender=groupGender.substring(groupGender.indexOf('/')+1, groupGender.length());//.toLowerCase();
        }
        
        // Clear event and athlete box
        EventC.removeAllItems();
        EventC.setEnabled(false);
        globalData.currentEvent = null;
        AthleteC.removeAllItems();
        AthleteC.setEnabled(false);
        
        // Load contents of event box
        HashSet validEvents = database.getEvents(globalData.currentAge,globalData.currentGroup, globalData.currentGender);
        
        int i;
        if (validEvents != null) {
            EventC.addItem(globalData.eventInfo[0]);
            globalData.eventCount = 0;
            for (i = 0; i < Array.getLength(globalData.eventInfo); i++) {
                if (validEvents.contains(globalData.eventInfo[i])) 
                {
                    EventC.addItem(globalData.eventInfo[i]);
                    EventC.setEnabled(true);
                    globalData.eventCount++;
                }
            }

        }
        //just load the data to thet screen
        showSummary(false);
    }//GEN-LAST:event_GroupGenderCActionPerformed

    private void ResetBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ResetBActionPerformed
        if(JOptionPane.showConfirmDialog(null, "Do you want to reset the athlete?" , "Request Confirmation", JOptionPane.YES_NO_OPTION)==JOptionPane.NO_OPTION)
            return;
        
        //reset the data related to the athlete
        database.resetNSave(globalData.currentAthlete);
        
        //close the athlete
        closeAthlete();
        
        //reopen the athlete
        openAthlete();
        
        //set  appopriate buttons
        StartB.setEnabled(true);
        ResetB.setEnabled(false);
        ShowB.setEnabled(false);
    }//GEN-LAST:event_ResetBActionPerformed

    private void AthleteCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AthleteCActionPerformed
        //closes any active athlete if any

        closeAthlete();

        if (AthleteC.getSelectedItem() != null && !((String) AthleteC.getSelectedItem()).equals(""))
            openAthlete();
        
        showSummary(false);
        
        
        
    }//GEN-LAST:event_AthleteCActionPerformed


    //checks for valid entries
    private boolean checkValidEntries()
    {
        //judge A
        if(ValidRange(judge.judgeType.judgeA,scoreAF.getText())==false)
        {
            JOptionPane.showMessageDialog(null, "Please enter valid Judge A score" , "Error", JOptionPane.OK_OPTION);
            scoreAF.grabFocus();
            return false;
        }
        
        //judge B
        if(ValidRange(judge.judgeType.judgeB,scoreBF.getText())==false)
        {
            JOptionPane.showMessageDialog(null, "Please enter valid Judge B score" , "Error", JOptionPane.OK_OPTION);
            scoreBF.grabFocus();
            return false;
        }
        
        //judge C
        if(ValidRange(judge.judgeType.judgeC,scoreCF.getText())==false)
        {
            JOptionPane.showMessageDialog(null, "Please enter valid Judge C score" , "Error", JOptionPane.OK_OPTION);
            scoreCF.grabFocus();
            return false;
        }

        //deductions
        try 
        {
            double temp_deduct = Double.parseDouble(HeadDeduction.getText());
            if (temp_deduct < 0)
            {
                JOptionPane.showMessageDialog(null, "Please enter positive deduction value" , "Error", JOptionPane.OK_OPTION);
                HeadDeduction.grabFocus();
                return false;
            }
        }catch (NumberFormatException e) 
        {
             //show the error
            JOptionPane.showMessageDialog(null, "Head Judge Submition failed. Please enter 0.0 in score/deduct if no values are to be entered" , "Error", JOptionPane.OK_OPTION);
            return false;
        }
        return true;
    }
    private void ShowBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ShowBActionPerformed
        
        //stop the athlete first
        stopAthlete();
        //freeze athlete
        freezeAthlete();
        
        //used for simple judging
        globalData.currentAthlete.sjJudgeASummary=SummaryAF.getText();
        globalData.currentAthlete.sjJudgeBSummary=SummaryBF.getText();
        globalData.currentAthlete.sjJudgeCSummary=SummaryCF.getText();
        
        //judge A
        if(ValidRange(judge.judgeType.judgeA,scoreAF.getText()))
        {
            globalData.currentAthlete.sjJudgeA=scoreAF.getText();
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Please enter valid Judge A score" , "Error", JOptionPane.OK_OPTION);
            scoreAF.grabFocus();
            return;
        }
        
        //judge B
        if(ValidRange(judge.judgeType.judgeB,scoreBF.getText()))
        {
            globalData.currentAthlete.sjJudgeB=scoreBF.getText();
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Please enter valid Judge B score" , "Error", JOptionPane.OK_OPTION);
            scoreBF.grabFocus();
            return;
        }
        
        //judge C
        if(ValidRange(judge.judgeType.judgeC,scoreCF.getText()))
        {
            globalData.currentAthlete.sjJudgeC=scoreCF.getText();
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Please enter valid Judge C score" , "Error", JOptionPane.OK_OPTION);
            scoreCF.grabFocus();
            return;
        }

        //deductions
        try 
        {
            double temp_deduct = Double.parseDouble(HeadDeduction.getText());
            if (temp_deduct < 0)
            {
                JOptionPane.showMessageDialog(null, "Please enter positive deduction value" , "Error", JOptionPane.OK_OPTION);
                HeadDeduction.grabFocus();
                return;
            }
            // bad deduction, needs a reason if > 0
            if ((temp_deduct > 0 && (Reason.getText() == null || Reason.getText().length() <= 0))) 
            {
                JOptionPane.showMessageDialog(null, "Please enter reason for the deduction" , "Error", JOptionPane.OK_OPTION);
                Reason.grabFocus();
                return;
            }
        }catch (NumberFormatException e) 
        {
             //show the error
            JOptionPane.showMessageDialog(null, "Head Judge Submition failed. Please enter 0.0 in score/deduct if no values are to be entered" , "Error", JOptionPane.OK_OPTION);
            return;
        }
        globalData.currentAthlete.sjDeductions=HeadDeduction.getText();
        globalData.currentAthlete.setReason(Reason.getText());
        
        try 
        {
            double temp_deduct = Double.parseDouble(finalF.getText());
            if(temp_deduct<0 || temp_deduct>10)
            {
                //throw new NumberFormatException();
                //show the error
                JOptionPane.showMessageDialog(null, "Please enter valid final score" , "Error", JOptionPane.OK_OPTION);
                finalF.grabFocus();
                return;
            }
            globalData.currentAthlete.sjFinal=finalF.getText();
        }
        catch (NumberFormatException e) 
        {
             //show the error
            JOptionPane.showMessageDialog(null, "Please enter valid final score" , "Error", JOptionPane.OK_OPTION);
            finalF.grabFocus();
            return;
        }
       
        
        
        
        //save the data to the database
        database.MarshalSimple(globalData.currentAthlete,globalData.scoringSystem);
        
        //show output to the projector screen
        showSummary(true);    

        //enable reset athlete button
        ResetB.setEnabled(true);
        
        //other enable buttons
        GroupGenderC.setEnabled(true);
        EventC.setEnabled(true);
        AthleteC.setEnabled(true);

        //head judge buttons and fields should be disabled
        Head2.setEnabled(false);
        HeadDeduction.setEnabled(false);
        ReasonCL.setEnabled(false);
        Reason.setEnabled(false);
        EvaluateB.setEnabled(false);
        
        
        scoreAL.setEnabled(false);
        scoreAF.setEnabled(false);
        SummaryAL.setEnabled(false);
        SummaryAF.setEnabled(false);
            
        scoreBL.setEnabled(false);
        scoreBF.setEnabled(false);
        SummaryBL.setEnabled(false);
        SummaryBF.setEnabled(false);
            
        scoreCL.setEnabled(false);
        scoreCF.setEnabled(false);
        SummaryCL.setEnabled(false);
        SummaryCF.setEnabled(false);
        
       
        //HeadDeduction.setText("0.0");
        //Reason.setText("");
        
    }//GEN-LAST:event_ShowBActionPerformed

    private void EventCActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EventCActionPerformed
        loadEvent();
    }//GEN-LAST:event_EventCActionPerformed
   
    private void StartBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StartBActionPerformed
        startAthlete();
    }//GEN-LAST:event_StartBActionPerformed

    private void ExitMActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExitMActionPerformed
        System.exit(0);
    }//GEN-LAST:event_ExitMActionPerformed

    private void scoreBFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scoreBFActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_scoreBFActionPerformed

    private void EvaluateBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EvaluateBActionPerformed
        //checks for valid entries
        if(checkValidEntries()==false)
            return;
        
        double judgeAScore=0.0;
        double judgeBScore=0.0;
        double judgeCScore=0.0;
        double deduction=0.0;
        double finalScore=0.0;

        try 
        {
            judgeAScore = Double.parseDouble(scoreAF.getText());
        }
        catch (NumberFormatException e) 
        {
        }

        try 
        {
            judgeBScore = Double.parseDouble(scoreBF.getText());
        }
        catch (NumberFormatException e) 
        {
        }

        try 
        {
            judgeCScore = Double.parseDouble(scoreCF.getText());            
        }
        catch (NumberFormatException e) 
        {
        }

        try 
        {
            deduction = Double.parseDouble(HeadDeduction.getText());
        }
        catch (NumberFormatException e) 
        {
        }
        finalScore=(judgeAScore+judgeBScore+judgeCScore)-deduction;
        finalF.setText(String.format("%.2f",Double.valueOf(finalScore)));    
    }//GEN-LAST:event_EvaluateBActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainForm().setVisible(true);
            }
        });
    }
    
    // sets up database
    void initDatabase()
    {
        try {
            database=new Database();
        } catch (Exception e) {
            System.err.println(e);
            System.exit(1);
        }
    }
    
    void initSoftware()
    {
        HashSet groupList=database.getGroups();
        for (int i = 0; i < Array.getLength(globalData.groupInfo); i++)
        {
            if(groupList.contains(globalData.groupInfo[i]))
                GroupGenderC.addItem(globalData.groupInfo[i]);
        }
        
        showSummary(false);
    }

    private void loadEvent()
    {
        //close open athlete if any
        closeAthlete();

        //remove all athlete list from the drop down list
        AthleteC.removeAllItems();
        AthleteC.setEnabled(false);

        //set current event on the global pointer
        globalData.currentEvent = new event();
        globalData.currentEvent.setevent((String)EventC.getSelectedItem());


        if (globalData.currentEvent.getevent() == null)
        {
            return;
        }

        // get athlete list from database
        Vector athletes = null;


        //save old scoring system
        int oldScoringSystem=globalData.scoringSystem;

        //get the type of the scoring sytem used
        if(globalData.currentGroup.length()>0 && globalData.currentEvent.getevent().length()>0)
            globalData.scoringSystem=database.getScoringSystem(globalData.currentGroup,globalData.currentEvent.getevent());
        else
            globalData.scoringSystem=2;

        //if the scoring system changed
        if(globalData.scoringSystem!=oldScoringSystem || globalData.getUserAdded())
        {
            //send data to all the judges
            for(int i=0;i<(globalData.totalJudges-1);i++)
            {
                // If the client is connected, then you can erase its data...
                if(globalData.isJudgeConnected(i)==true)
                {
                    globalData.clients[i].sendMessage("SCOR "+ globalData.scoringSystem);
                }
                else
                {
                    if(globalData.scoringSystem==0) //traditional
                        globalData.judges[i].setType(judge.judgeType.judgeB);
                }
            }
            //set the user added flag to false as the processing is done
            globalData.setUserAdded(false);
        }

        //get the poingter to the current athletes based on group,gender and event
        athletes = database.getAthletes(globalData.currentAge, globalData.currentGroup, globalData.currentGender, globalData.currentEvent.getevent());

        if (athletes != null && athletes.size() > 0)
        {
            // enable athlete combo box
            AthleteC.setEnabled(true);
            int i;
            AthleteC.addItem("");

            //load names of all the athletes
            for (i = 0; i < athletes.size(); i++)
            {
                String athlete_name = (String) athletes.get(i);
                AthleteC.addItem(athlete_name);
            }
        }

        showSummary(false);
    }
    
    //all the necessary action to open the athlete
    void openAthlete() 
    {
        //get the name of the selected athlete
        String name = (String) AthleteC.getSelectedItem();
        //use the name along with event, gender info to create athlete in memory
        globalData.currentAthlete = new athlete(globalData.currentGroup, globalData.currentGender,globalData.currentEvent.getevent(), name);

        //retrive the value of current athlete in that event if any
        database.UnmarshalSimple(globalData.currentAthlete);
        
        //set the global time
        globalData.diffTime = globalData.currentAthlete.getTime();
        
//        // fill in head-judge data
//        if (globalData.currentAthlete.getJudgeVector(globalData.totalJudges-1) != null)
//        {
//            Vector data = globalData.currentAthlete.getJudgeVector(globalData.totalJudges-1);
//            
//            //set score given by head judge
//            //if (data.size() >= 1) 
//            //    HeadScore.setText(String.format("%.2f", (Double) (data.elementAt(0))));
//
//            //set deduction if any
//            if (data.size() >= 2) 
//                HeadDeduction.setText(String.format("%.2f", (Double) (data.elementAt(1))));
//            
//            //set reason for duductions if any
//            if (globalData.currentAthlete.getReason() != null && globalData.currentAthlete.getReason().length() > 0)
//                Reason.setText(globalData.currentAthlete.getReason());
//
//        }
          
        //load up information in screen
        //it will not show projector information
        showSummary(false);
        
        //check if the reset button should be enabled based on if the athlete has 
        //competed in that event before
        if (globalData.currentAthlete.hasCompeted() == false)
        {
            StartB.setEnabled(true);
            ResetB.setEnabled(false);
           
            scoreAF.setText("");
            scoreBF.setText("");
            scoreCF.setText("");
            SummaryAF.setText("");
            SummaryBF.setText("");
            SummaryCF.setText("");            
            HeadDeduction.setText("0.0");
            Reason.setText("");
            finalF.setText("");
        }
        else 
        {
            StartB.setEnabled(false);
            ShowB.setEnabled(true);
            ResetB.setEnabled(true);
            
            SummaryAF.setText(globalData.currentAthlete.sjJudgeASummary);
            SummaryBF.setText(globalData.currentAthlete.sjJudgeBSummary);
            SummaryCF.setText(globalData.currentAthlete.sjJudgeCSummary);

            scoreAF.setText(globalData.currentAthlete.sjJudgeA);
            scoreBF.setText(globalData.currentAthlete.sjJudgeB);
            scoreCF.setText(globalData.currentAthlete.sjJudgeC);
            //SummaryAF.setText("");
            //SummaryBF.setText("");
            //SummaryCF.setText("");  
            if(globalData.currentAthlete.sjDeductions.trim().length()>0)
                HeadDeduction.setText(globalData.currentAthlete.sjDeductions);
            else
                HeadDeduction.setText("0.0");
            Reason.setText(globalData.currentAthlete.getReason());
            finalF.setText(globalData.currentAthlete.sjFinal);
        }
    }
    
    void startAthlete() 
    {
        //disable buttons
        GroupGenderC.setEnabled(false);
        EventC.setEnabled(false);
        AthleteC.setEnabled(false);
        StartB.setEnabled(false);
        ShowB.setEnabled(true);
        
        if(globalData.scoringSystem==0)    //Traditional system
        {
          
            scoreBL.setEnabled(true);
            scoreBF.setEnabled(true);            
            SummaryBL.setEnabled(true);
            SummaryBF.setEnabled(true);
                                  
            Head2.setEnabled(true);
            HeadDeduction.setEnabled(true);
            ReasonCL.setEnabled(true);
            Reason.setEnabled(true);
            
            finalScoreL.setEnabled(true);
            finalF.setEnabled(true);
            EvaluateB.setEnabled(true);
                        
        }
        else if(globalData.scoringSystem==1)// Nandu AB compulsory
        {

            scoreAL.setEnabled(true);
            scoreAF.setEnabled(true);
            SummaryAL.setEnabled(true);
            SummaryAF.setEnabled(true);
            
            scoreBL.setEnabled(true);
            scoreBF.setEnabled(true);
            SummaryBL.setEnabled(true);
            SummaryBF.setEnabled(true);
                                    
            Head2.setEnabled(true);
            HeadDeduction.setEnabled(true);
            ReasonCL.setEnabled(true);
            Reason.setEnabled(true);
            
            finalScoreL.setEnabled(true);
            finalF.setEnabled(true);
            EvaluateB.setEnabled(true);
        }
        else //Nandu ABC
        {
            scoreAL.setEnabled(true);
            scoreAF.setEnabled(true);
            SummaryAL.setEnabled(true);
            SummaryAF.setEnabled(true);
            
            scoreBL.setEnabled(true);
            scoreBF.setEnabled(true);
            SummaryBL.setEnabled(true);
            SummaryBF.setEnabled(true);
            
            scoreCL.setEnabled(true);
            scoreCF.setEnabled(true);
            SummaryCL.setEnabled(true);
            SummaryCF.setEnabled(true);
                                    
            Head2.setEnabled(true);
            HeadDeduction.setEnabled(true);
            ReasonCL.setEnabled(true);
            Reason.setEnabled(true);
            
            finalScoreL.setEnabled(true);
            finalF.setEnabled(true);
            EvaluateB.setEnabled(true);
        }
        
        

        //enable stop button
        //StopB.setEnabled(true);
     
        //record currned time
        globalData.startTime=System.currentTimeMillis();
        globalData.endTime=System.currentTimeMillis();
        globalData.currentAthlete.setSetupInfo(globalData.getSetupInfo());



        if( globalData.currentAthlete.hasCompeted()==false)
        {
            //set the judge type
            for(int i=0;i<globalData.totalJudges;i++)
            {
                globalData.currentAthlete.setJudgeConnected(i,globalData.judgesConnected[i]);
                globalData.currentAthlete.setJudgeType(i,globalData.judges[i].type);
            }
        }

        //get the index of athlete and event
        int eventIndex=EventC.getSelectedIndex();
        int athleteIndex=AthleteC.getSelectedIndex();
        
        
        for(int i=0;i<(globalData.totalJudges-1);i++)
        {
            // If the client is connected, then you can erase its data...
            if(globalData.isJudgeConnected(i)==true) 
            {   
                //debug info written to the text file
                globalData.judges[i].beginAthlete(globalData.currentAthlete.getName());
                
                //load an athlete and send its info to the corresponding judge
                globalData.clients[i].sendMessage("ATHL "+ globalData.scoringSystem +" " +globalData.currentAthlete.toString());
                globalData.clients[i].sendMessage("EVNT "+ globalData.currentGroup + " "
                                                         + globalData.currentGender + " "
                                                         + globalData.currentEvent.getevent());
                globalData.clients[i].individiualDifficultyJudged=0;
                globalData.clients[i].location=0;
            }
        }
        
        globalData.athleteActive=true;
        globalData.athleteScorable = true;
    }
    
    //actions for stopping timing, but still allowing judges to
    //entering their scores
    void stopAthlete() 
    {
        if (globalData.athleteActive) 
        {
            //disable buttons
            //StopB.setEnabled(false);
            
            //enable buttons
            //GetScoresB.setEnabled(true);
                        
            //unset athlete's active status
            globalData.athleteActive = false;
            
            //record the ending time
            globalData.endTime = System.currentTimeMillis();
        }
    }
    
    void freezeAthlete() 
    {
        // send stop message to clients
        for (int i = 0; i < (globalData.totalJudges-1); i++) 
        {
            if (globalData.isJudgeConnected(i)==true)
            {
                globalData.clients[i].sendMessage("ATST");
            }
        }
        //disable buttons
        //GetScoresB.setEnabled(false);
        
        //enable buttons
        ShowB.setEnabled(true);
        //if(globalData.scoringSystem==0)
        //EnterScore.setEnabled(true);
        // enable head judge buttons and fields
        //Head1.setEnabled(true);
        //HeadScore.setEnabled(true);
        Head2.setEnabled(true);
        HeadDeduction.setEnabled(true);
        ReasonCL.setEnabled(true);
        Reason.setEnabled(true);
        //HeadSubmitB.setEnabled(true);
        
        // unset athlete's scorable status
        globalData.athleteScorable = false;
    }
    //checks if the score is in valid range
    private boolean ValidRange(judge.judgeType jType,String scoreString)
    {
        double score;
        scoreString=scoreString.trim();
        if(scoreString.length()==0)
        {
            score=0.0;
        }
        else
        {
            try 
            {
                 score = Double.parseDouble(scoreString);             
            } catch (NumberFormatException e) 
            {
                return false;
            }
        }
        return ValidRange(jType,score);
    }
    
    //checks if the score is in valid range
    private boolean ValidRange(judge.judgeType jType,double score)
    {
        if(jType==judge.judgeType.judgeA)
        {
            if(globalData.scoringSystem==0)    //Traditional system
                return(0.0<=score && score<=0.0);
            else if(globalData.scoringSystem==1)// Nandu AB compulsory
                return (0 <= score  && score <= 5);
            return (0 <= score  && score <= 5); //Nandu ABC
        }
        else if(jType==judge.judgeType.judgeB)
        {
            if(globalData.scoringSystem==0)    //Traditional system
                return(0.0<=score && score<=10.0);
            else if(globalData.scoringSystem==1)// Nandu AB compulsory
                return (0 <= score  && score <= 5);
            return (0 <= score  && score <= 3); //Nandu ABC
        }
        else
        {
             if(globalData.scoringSystem==0)    //Traditional system
                return(0.0<=score && score<=0.0);
             else if(globalData.scoringSystem==1)// Nandu AB compulsory
                return (0 <= score  && score <= 0);
             return (0 <= score  && score <= 3); //Nandu ABC
        }
    }
    
    //returns the valid range
    private String getValidRangeString()
    {
        String range="Valid range : ";
        // 0 Traditional System
        if(globalData.scoringSystem==0)//Traditional system
            range=range+"[ 0.0 - 10.0]";
        else if(globalData.scoringSystem==1)// Nandu AB compulsory
            range=range+"[ 0.0 - 5.0]";
        else
             range=range+"[ 0.0 - 3.0]";//Nandu ABC
        return range;
    }
    
    

    //Pefromed when head judge hits submit
    void headJudgeSubmitAction() 
    {
        Vector data = new Vector();

        try 
        {
            //double temp_score = Double.parseDouble(HeadScore.getText());
            double temp_deduct = Double.parseDouble(HeadDeduction.getText());
 
            // bad score
//            if (temp_score!=0 && !ValidRange(temp_score)) 
//            {
//                JOptionPane.showMessageDialog(null, "Please enter valid score range. " + getValidRangeString(), "Error", JOptionPane.OK_OPTION);
//                HeadScore.grabFocus();
//                return;
//            }
            
            if (temp_deduct < 0)
            {
                JOptionPane.showMessageDialog(null, "Please enter positive deduction value" , "Error", JOptionPane.OK_OPTION);
                HeadDeduction.grabFocus();
                return;
            }
            
            // bad deduction, needs a reason if > 0
            if ((temp_deduct > 0 && (Reason.getText() == null || Reason.getText().length() <= 0))) 
            {
                JOptionPane.showMessageDialog(null, "Please enter reason for the deduction" , "Error", JOptionPane.OK_OPTION);
                Reason.grabFocus();
                return;
            }
 
        } catch (NumberFormatException e) 
        {
             //show the error
            JOptionPane.showMessageDialog(null, "Head Judge Submition failed. Please enter 0.0 in score/deduct if no values are to be entered" , "Error", JOptionPane.OK_OPTION);
            return;
        }
        //copy the data to athlete pointer
        //data.addElement(Double.parseDouble(HeadScore.getText()));
        data.addElement(Double.parseDouble(HeadDeduction.getText()));
        globalData.currentAthlete.setJudgeVector(globalData.totalJudges-1,data);
        globalData.currentAthlete.setReason(Reason.getText());
        
        // disable buttons
        //Head1.setEnabled(false);
        //HeadScore.setEnabled(false);
        Head2.setEnabled(false);
        HeadDeduction.setEnabled(false);
        ReasonCL.setEnabled(false);
        Reason.setEnabled(false);
        //HeadSubmitB.setEnabled(false);
        
        // enable buttons
       // HeadUndoB.setEnabled(true);
    }
    
    //undo button hit by head judge
    void headJudgeUndoAction() 
    {
        Vector temp=new Vector();
        globalData.currentAthlete.setJudgeVector(globalData.totalJudges-1,temp);
        
        // disable buttons
        //HeadUndoB.setEnabled(false);
        
        // enable buttons
        //Head1.setEnabled(true);
        //HeadScore.setEnabled(true);
        Head2.setEnabled(true);
        HeadDeduction.setEnabled(true);
        ReasonCL.setEnabled(true);
        Reason.setEnabled(true);
        //HeadSubmitB.setEnabled(true);
    }
    
    //all the necessary action to close the athlete
    void closeAthlete() 
    {
        //check if any athletes are open
        if (globalData.currentAthlete == null) 
            return;
            
        //send close athlete data to all of the connecting judges
        for(int i=0;i<(globalData.totalJudges-1);i++) 
        {
            if(globalData.isJudgeConnected(i)==true)
            {
                globalData.judges[i].endAthlete();
                globalData.clients[i].sendMessage("ATFN");
            }
        }
        
        //clear all data
        globalData.currentAthlete.clearJudgesVector(false);
        
        //enable buttons
        StartB.setEnabled(false);
        GroupGenderC.setEnabled(true);
        EventC.setEnabled(true);
        AthleteC.setEnabled(true);
        
    
        // disable buttons
        //StopB.setEnabled(false);
        ShowB.setEnabled(false);
        //EnterScore.setEnabled(false);
        ResetB.setEnabled(false);
        
        //head judge buttons and fields should be disabled
        //Head1.setEnabled(false);
        //HeadScore.setEnabled(false);
        //HeadScore.setText("0.0");
        Head2.setEnabled(false);
        HeadDeduction.setEnabled(false);
        //HeadDeduction.setText("0.0");
        ReasonCL.setEnabled(false);
        Reason.setEnabled(false);
        //Reason.setText("");
        //HeadSubmitB.setEnabled(false);
        //HeadUndoB.setEnabled(false);
        
        scoreAL.setEnabled(false);
        scoreAF.setEnabled(false);
        SummaryAL.setEnabled(false);
        SummaryAF.setEnabled(false);
        scoreBL.setEnabled(false);
        scoreBF.setEnabled(false);
        SummaryBL.setEnabled(false);
        SummaryBF.setEnabled(false);
        scoreCL.setEnabled(false);
        scoreCF.setEnabled(false);
        SummaryCL.setEnabled(false);
        SummaryCF.setEnabled(false);
        finalScoreL.setEnabled(false);
        finalF.setEnabled(false);
        EvaluateB.setEnabled(false);
        
        globalData.athleteActive=false;
        globalData.diffTime = 0;
        globalData.currentAthlete = null;
 
    }
    
    public void showSummary(boolean withScore)
    {
        //if the form doesn't exist create one
        if(finalSummary==null)
            finalSummary=new Summary(null, false);
        
        //make final summary visible
        if (finalSummary.isVisible() == false)
            finalSummary.setVisible(true);
        
        //clear previous data if any
        finalSummary.clear();
        
        finalSummary.setTitle(globalData.titleName);
        
        //add data to the form
        finalSummary.setGroupGender(globalData.currentGroup + ".  " + globalData.currentGender+"  "+globalData.currentAge);

        //set event
        if (globalData.currentEvent != null) 
            finalSummary.setEvent(globalData.currentEvent.getevent());

        //set athlete data
        if (globalData.currentAthlete != null) 
        {
            String temp = globalData.currentAthlete.getName();
            String name = temp.substring(0, temp.lastIndexOf('(') - 1);
            finalSummary.setName(name);
        }
        
        //set athlete score
        if (withScore) 
        {
            //bad hack to show scores from all judges
            if(globalData.scoringSystem==0)  // 0 Traditional System
            {
                finalSummary.setMistake(globalData.currentAthlete.getJudgesData(globalData.scoringSystem));
                
            }
            else if(globalData.scoringSystem==1)  //1 New Traditional System
            {
                finalSummary.setScoreA(globalData.currentAthlete.getAScoreSimple(),globalData.currentAthlete.sjJudgeASummary);
                finalSummary.setMistake(globalData.currentAthlete.MarshalAgreeA());            
            }
            else    // 2 Nandu System
            {
                finalSummary.setScoreA(globalData.currentAthlete.getAScoreSimple(),globalData.currentAthlete.sjJudgeASummary);
                finalSummary.setScoreC(globalData.currentAthlete.getCScoreSimple(),globalData.currentAthlete.sjJudgeCSummary);
                finalSummary.setMistake(globalData.currentAthlete.getDeductionsSimple());
            }
            int currentRanking=database.getRankingSimple(globalData.currentAthlete,globalData.currentEvent.getevent(),globalData.currentAge,globalData.currentGroup,globalData.currentGender);
            finalSummary.setRank(""+currentRanking);
            finalSummary.setScoreB(globalData.currentAthlete.getBScoreSimple(),globalData.currentAthlete.sjJudgeBSummary);
            finalSummary.setDeduction(globalData.currentAthlete.getDeductionsSimple(),globalData.currentAthlete.getReason());
            finalSummary.setFinalScore(globalData.currentAthlete.getFinalScoreSimple());
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox AthleteC;
    private javax.swing.JButton EvaluateB;
    private javax.swing.JComboBox EventC;
    private javax.swing.JMenuItem ExitM;
    private javax.swing.JComboBox GroupGenderC;
    private javax.swing.JTextArea Head2;
    private javax.swing.JTextField HeadDeduction;
    private javax.swing.JPanel MainP;
    private javax.swing.JButton PublishB;
    private javax.swing.JTextField Reason;
    private javax.swing.JTextArea ReasonCL;
    private javax.swing.JButton ResetB;
    private javax.swing.JButton ShowB;
    private javax.swing.JButton StartB;
    private javax.swing.JTextField SummaryAF;
    private javax.swing.JTextArea SummaryAL;
    private javax.swing.JTextField SummaryBF;
    private javax.swing.JTextArea SummaryBL;
    private javax.swing.JTextField SummaryCF;
    private javax.swing.JTextArea SummaryCL;
    private javax.swing.JTextField finalF;
    private javax.swing.JLabel finalScoreL;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTextField scoreAF;
    private javax.swing.JLabel scoreAL;
    private javax.swing.JTextField scoreBF;
    private javax.swing.JLabel scoreBL;
    private javax.swing.JTextField scoreCF;
    private javax.swing.JLabel scoreCL;
    // End of variables declaration//GEN-END:variables
    
}
